from flask import Flask, jsonify, request
from flask_cors import CORS
import json
import random
from datetime import datetime

app = Flask(__name__)
CORS(app)

class StateAI:
    def __init__(self, name, abbreviation):
        self.name = name
        self.abbreviation = abbreviation
        self.troops = 100000  # 初始兵力10万
        self.territories = [name]  # 初始领土
        self.relations = {}  # 外交关系
        self.wars = []  # 战争状态
        self.alliances = []  # 联盟
        
    def to_dict(self):
        return {
            'name': self.name,
            'abbreviation': self.abbreviation,
            'troops': self.troops,
            'territories': self.territories,
            'relations': self.relations,
            'wars': self.wars,
            'alliances': self.alliances
        }

class CivilWarSimulator:
    def __init__(self):
        self.states = {}
        self.turn = 0
        self.logs = []
        self.initialize_states()
        
    def initialize_states(self):
        # 美国50个州
        states_data = [
            "Alabama", "Alaska", "Arizona", "Arkansas", "California",
            "Colorado", "Connecticut", "Delaware", "Florida", "Georgia",
            "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas",
            "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
            "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
            "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico",
            "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma",
            "Oregon", "Pennsylvania", "Rhode Island", "South Carolina",
            "South Dakota", "Tennessee", "Texas", "Utah", "Vermont",
            "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"
        ]
        
        abbreviations = {
            "Alabama": "AL", "Alaska": "AK", "Arizona": "AZ", "Arkansas": "AR",
            "California": "CA", "Colorado": "CO", "Connecticut": "CT", "Delaware": "DE",
            "Florida": "FL", "Georgia": "GA", "Hawaii": "HI", "Idaho": "ID",
            "Illinois": "IL", "Indiana": "IN", "Iowa": "IA", "Kansas": "KS",
            "Kentucky": "KY", "Louisiana": "LA", "Maine": "ME", "Maryland": "MD",
            "Massachusetts": "MA", "Michigan": "MI", "Minnesota": "MN", "Mississippi": "MS",
            "Missouri": "MO", "Montana": "MT", "Nebraska": "NE", "Nevada": "NV",
            "New Hampshire": "NH", "New Jersey": "NJ", "New Mexico": "NM", "New York": "NY",
            "North Carolina": "NC", "North Dakota": "ND", "Ohio": "OH", "Oklahoma": "OK",
            "Oregon": "OR", "Pennsylvania": "PA", "Rhode Island": "RI", "South Carolina": "SC",
            "South Dakota": "SD", "Tennessee": "TN", "Texas": "TX", "Utah": "UT",
            "Vermont": "VT", "Virginia": "VA", "Washington": "WA", "West Virginia": "WV",
            "Wisconsin": "WI", "Wyoming": "WY"
        }
        
        for state in states_data:
            self.states[state] = StateAI(state, abbreviations[state])
            
    def next_turn(self):
        self.turn += 1
        self.logs.append(f"=== 第{self.turn}回合 ===")
        
        # 每个AI进行决策
        for state_name, state in self.states.items():
            self.ai_decision(state)
            
        # 处理战争
        self.process_wars()
        
        # 招兵
        self.recruit_troops()
        
        return {
            'turn': self.turn,
            'states': {name: state.to_dict() for name, state in self.states.items()},
            'logs': self.logs[-20:]  # 只返回最近20条日志
        }
        
    def ai_decision(self, state):
        # 简单的AI决策逻辑
        if state.troops < 50000 and state.wars:
            # 兵力不足时可能求和
            for enemy in state.wars:
                if random.random() < 0.3:
                    self.logs.append(f"{state.name} 向 {enemy} 求和")
                    self.peace_negotiation(state.name, enemy)
                    
        elif state.troops > 150000:
            # 兵力充足时可能宣战
            targets = [s for s in self.states.keys() 
                      if s != state.name and s not in state.wars and s not in state.alliances]
            if targets:
                target = random.choice(targets)
                if random.random() < 0.2:
                    self.declare_war(state.name, target)
                    
        # 可能形成联盟
        if not state.alliances and random.random() < 0.1:
            allies = [s for s in self.states.keys() 
                     if s != state.name and s not in state.wars]
            if allies:
                ally = random.choice(allies)
                self.form_alliance(state.name, ally)
                
    def declare_war(self, attacker, defender):
        if defender not in self.states[attacker].wars:
            self.states[attacker].wars.append(defender)
            self.states[defender].wars.append(attacker)
            self.logs.append(f"{attacker} 向 {defender} 宣战！")
            
    def peace_negotiation(self, state1, state2):
        if state2 in self.states[state1].wars:
            self.states[state1].wars.remove(state2)
            self.states[state2].wars.remove(state1)
            self.logs.append(f"{state1} 和 {state2} 达成和平协议")
            
    def form_alliance(self, state1, state2):
        if state2 not in self.states[state1].alliances:
            self.states[state1].alliances.append(state2)
            self.states[state2].alliances.append(state1)
            self.logs.append(f"{state1} 和 {state2} 结成联盟")
            
    def process_wars(self):
        # 处理所有战争
        processed_pairs = set()
        
        for state_name, state in self.states.items():
            for enemy in state.wars[:]:  # 使用切片避免修改列表
                pair = tuple(sorted([state_name, enemy]))
                if pair not in processed_pairs:
                    self.battle(state_name, enemy)
                    processed_pairs.add(pair)
                    
    def battle(self, state1, state2):
        troops1 = self.states[state1].troops
        troops2 = self.states[state2].troops
        
        if troops1 > troops2:
            winner, loser = state1, state2
        elif troops2 > troops1:
            winner, loser = state2, state1
        else:
            # 兵力相同时随机决定
            winner, loser = random.choice([(state1, state2), (state2, state1)])
            
        # 胜利者获得领土
        if loser in self.states[winner].territories:
            self.states[winner].territories.append(loser)
            
        # 兵力损失
        loss_ratio = 0.3
        self.states[state1].troops = int(troops1 * (1 - loss_ratio))
        self.states[state2].troops = int(troops2 * (1 - loss_ratio))
        
        self.logs.append(f"{winner} 击败 {loser}！")
        
    def recruit_troops(self):
        # 每控制一个州获得1万兵力
        for state_name, state in self.states.items():
            new_troops = len(state.territories) * 10000
            state.troops += new_troops
            if new_troops > 0:
                self.logs.append(f"{state_name} 招募了 {new_troops} 兵力")

# 全局模拟器实例
simulator = CivilWarSimulator()

@app.route('/api/state')
def get_states():
    return jsonify({
        'turn': simulator.turn,
        'states': {name: state.to_dict() for name, state in simulator.states.items()},
        'logs': simulator.logs[-20:]
    })

@app.route('/api/next_turn', methods=['POST'])
def next_turn():
    result = simulator.next_turn()
    return jsonify(result)

@app.route('/api/reset', methods=['POST'])
def reset():
    global simulator
    simulator = CivilWarSimulator()
    return jsonify({'status': 'reset'})

if __name__ == '__main__':
    app.run(debug=True, port=5000)
